//
//  ViewController.m
//  TestQR
//
//  Created by 王声远 on 16/6/19.
//  Copyright © 2016年 anody. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)];
    [self.view addSubview:imgView];
    [self ciImageFromString:@"http://www.anody.com.cn" imgView:imgView imgSize:CGSizeMake(200, 200)];
}

//二维码生成且放到UIImageView显示
- (void)ciImageFromString:(NSString *)qrString imgView:(UIImageView *)imgView imgSize:(CGSize)size{
    
    imgView.backgroundColor = [UIColor redColor];
    imgView.contentMode = UIViewContentModeCenter;
    
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    [filter setValue:stringData forKey:@"inputMessage"];
    
    // 5.生成二维码
    CIImage *outputImage = filter.outputImage;
    CGFloat scale = size.width / CGRectGetWidth(outputImage.extent);
    CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale); // scale 为放大倍数
    CIImage *transformImage = [outputImage imageByApplyingTransform:transform];
    
    // 保存
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef imageRef = [context createCGImage:transformImage fromRect:transformImage.extent];
    UIImage *qrCodeImage = [UIImage imageWithCGImage:imageRef];
    
    // 6.设置生成好得二维码到imageView上
    imgView.image = qrCodeImage;
    
}

- (NSString *)stringFromCiImage:(CIImage *)ciimage {
    
    NSString *content = nil;
    if (!ciimage) {
        return nil;
    }
    
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode
                                              context:[CIContext contextWithOptions:nil]
                                              options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
    
    NSArray *features = [detector featuresInImage:ciimage];
    if (features.count) {
        for (CIFeature *feature in features) {
            if ([feature isKindOfClass:[CIQRCodeFeature class]]) {
                content = ((CIQRCodeFeature *)feature).messageString;
                break;
            }
        }
    } else {
        NSLog(@"未正常解析二维码图片, 请确保iphone5/5c以上的设备");
    }
    return content;
}

@end
